package com.sunfield.windpower.fragment;

import android.support.v7.widget.LinearLayoutManager;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.sunfield.baseframe.base.BaseFragment;
import com.sunfield.baseframe.http.HttpResult;
import com.sunfield.baseframe.util.JsonUtil;
import com.sunfield.windpower.R;
import com.sunfield.windpower.adapter.MessageAdapter;
import com.sunfield.windpower.bean.MessageInfo;
import com.sunfield.windpower.decoration.MessageDecoration;
import com.sunfield.windpower.http.HttpClient;
import com.sunfield.windpower.util.UserUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.List;

/**
 * 首页 消息
 * Created by wxl on 2017/2/6.
 */
@EFragment(R.layout.fragment_message)
public class MessageFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {
    @ViewById
    LRecyclerView rv_list;

    @Bean
    MessageAdapter adapter;
    @Bean
    HttpClient http;

    @AfterViews
    void init(){
        rv_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv_list.addItemDecoration(new MessageDecoration(getActivity()));
        rv_list.setAdapter(new LRecyclerViewAdapter(adapter));

        rv_list.setOnRefreshListener(this);
        rv_list.setOnLoadMoreListener(this);

        onRefresh();
        rv_list.setPullRefreshEnabled(true);
    }

    @Override
    public void onRefresh() {
        pageIndex = 0;
        getData();
    }

    @Override
    public void onLoadMore() {
        getData();
    }

    void getData(){
        http.getMessageList(UserUtil.getUserId(), String.valueOf(pageIndex), String.valueOf(pageSize));
    }

    @Override
    public void onHttpResult(HttpResult result) {
        super.onHttpResult(result);
        if(result.match(http, "getMessageList")){
            rv_list.refreshComplete();
            if(result.isSuccess()){
                List<MessageInfo> messageList = JsonUtil.GetEntityS(JsonUtil.GetJsonArrayByLevel(result.getJson(), "data", "info"), MessageInfo.class);
                if(pageIndex == 0){
                    adapter.clear();
                }
                adapter.addData(messageList);
                pageIndex ++;
                if(messageList.isEmpty()){
                    rv_list.setNoMore(true);
                }
            }
        }
    }
}
